import { zhooks } from 'ym-design'
const { useRequest } = zhooks
import dayjs from 'dayjs';
import { useState } from 'react';
function getArticle(): Promise<{ data: string; time: number }> {
  console.log('--getArticle111--cacheKey--');
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        data: Math.random() + 'Article，！',
        time: new Date().getTime(),
      });
    }, 1000);
  });
}

function getArticle2(): Promise<{ data: string; time: number }> {
  console.log('--getArticle222--cacheKey--');
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        data: Math.random() + 'Article，！',
        time: new Date().getTime(),
      });
    }, 1000);
  });
}

const CACHEKEYS = 'get-article-002222';
function Article({ fn }: { fn: Function }) {
  const { data, loading, run } = useRequest(fn, {
    cacheKey: CACHEKEYS,
    cacheTime: 10000,
    staleTime: 5000,
    onSuccess(data) {
      console.log('--onSuccess--data--', data);
    },
  });

  return (
    <div>
      <div>
        <p>data:{data && (data as any).data}</p>
        <p>data.time={data && dayjs(data?.time).get('second')}</p>
        <button disabled={loading} onClick={run}>
          run
        </button>
      </div>
    </div>
  );
}

function HookUseRequestCacheDataSharing() {
  console.log('---Article.run时，父组件刷新---');
  return (
    <div>
      <p>数据共享原理：useCachePlugin-- trigger(cacheKey, cachedData.data)---具有相同cackeKey的所有fetchInstance执行setState</p>
      <div>
        <p>-------Article1-------</p>
        <Article fn={getArticle} />
      </div>
      <div style={{ marginTop: 20 }}>
        <p>-------Article2-------</p>
        <Article fn={getArticle2} />
      </div>
    </div>
  );
}

export default HookUseRequestCacheDataSharing;